<template>
  <div class="app-container">
    <div class="search-bar" style="margin-bottom: 20px; display: flex; align-items: center; justify-content: space-between;">
      <div>
        <el-input
          v-model="queryParams.po_code"
          placeholder="请输入采购订单编号"
          size="small"
          style="width: 200px; margin-right: 10px;"
          clearable
        />
        <el-input
          v-model="queryParams.po_name"
          placeholder="请输入采购订单名称"
          size="small"
          style="width: 200px; margin-right: 10px;"
          clearable
        />
        <el-button type="primary" size="small" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="resetQuery" style="margin-left: 5px;">重置</el-button>
      </div>
      <el-button type="success" size="small" icon="el-icon-download" @click="handleStorage" style="margin-right: 30px;" :disabled="!canStorage">入库</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="detailList"
      style="width: 100%"
      empty-text="暂无到货通知数据"
    >
      <el-table-column prop="po_code" label="采购订单编号" align="center" show-overflow-tooltip width="150" fixed="left">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleViewDetails(scope.row.po_id)">{{ scope.row.po_code }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="po_name" label="采购订单名称" align="center" show-overflow-tooltip width="180" fixed="left" />
      <el-table-column prop="goods_code" label="货物编号" align="center" show-overflow-tooltip width="150" />
      <el-table-column prop="goods_name" label="货物名称" align="center" show-overflow-tooltip />
      <el-table-column prop="stock_sfn" label="规格型号" align="center" show-overflow-tooltip />
      <el-table-column prop="unit_name" label="单位" align="center" />
      <el-table-column prop="batch_code" label="批次号" align="center" show-overflow-tooltip width="150" />
      <el-table-column prop="unit_price" label="单价" align="center">
        <template slot-scope="scope">
          ¥{{ formatCurrency(scope.row.unit_price) }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity_num" label="采购数量" align="center">
        <template slot-scope="scope">
          {{ formatNumber(scope.row.quantity_num) }}
        </template>
      </el-table-column>
      <el-table-column prop="wait_num" label="待到货数量" align="center">
        <template slot-scope="scope">
          {{ formatNumber(scope.row.wait_num) }}
        </template>
      </el-table-column>
      <el-table-column prop="arrived_num" label="待入库数量" align="center">
        <template slot-scope="scope">
          {{ formatNumber(scope.row.arrived_num) }}
        </template>
      </el-table-column>
      <el-table-column prop="total_price" label="总价" align="center">
        <template slot-scope="scope">
          ¥{{ formatCurrency(scope.row.total_price) }}
        </template>
      </el-table-column>
      <el-table-column prop="delivery_num" label="本次配送" align="center" width="130">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.delivery_num"
            :min="0"
            :max="scope.row.wait_num"
            size="mini"
            style="width: 120px"
            placeholder="请输入数量"
            @change="handleDeliveryNumChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'warning'">
            {{ scope.row.status === '1' ? '运输中' : '已到货' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getArrivalNoticeList"
    />
    <el-dialog title="本次入库商品信息" :visible.sync="dialogVisible" width="1200px">
      <el-table :data="pagedSelectedItems" style="width: 100%">
        <el-table-column prop="po_code" label="采购订单编号" align="center" width="160" />
        <el-table-column prop="goods_code" label="货物编号" align="center" width="145" />
        <el-table-column prop="goods_name" label="货物名称" align="center" />
        <el-table-column prop="batch_code" label="批次号" align="center" width="160" />
        <el-table-column prop="unit_name" label="单位" align="center" width="80" />
        <el-table-column prop="unit_price" label="单价" align="center" width="100">
          <template slot-scope="scope">
            ¥{{ Number(scope.row.unit_price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="仓库" align="center" width="120" />
        <el-table-column prop="delivery_num" label="本次配送" align="center" width="100" />
      </el-table>
      <pagination
        v-show="selectedItemsTotal > 0"
        :total="selectedItemsTotal"
        :page.sync="storageDialogPage.pageNum"
        :limit.sync="storageDialogPage.pageSize"
        @pagination="handleStorageDialogPageChange"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleStorageCancel">取消</el-button>
        <el-button type="primary" @click="handleStorageConfirm">确定</el-button>
      </span>
    </el-dialog>
     <!-- 订单详情对话框 -->
    <el-dialog
      title="采购订单详情"
      :visible.sync="detailsVisible"
      width="70%"
      append-to-body
    >
      <div v-if="currentOrder">
        <el-descriptions title="订单信息" :column="3" border>
          <el-descriptions-item label="采购编号">{{ currentOrder.po_code }}</el-descriptions-item>
          <el-descriptions-item label="采购名称">{{ currentOrder.po_name }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ currentOrder.supplier_name }}</el-descriptions-item>
          <el-descriptions-item label="采购日期">{{ formatDate(currentOrder.purchase_date) }}</el-descriptions-item>
          <el-descriptions-item label="期望交货日期">{{ formatDate(currentOrder.expected_delivery_date) }}</el-descriptions-item>
          <el-descriptions-item label="订单总金额">¥{{ formatCurrency(currentOrder.total_amount) }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px;">商品信息</h3>
        <el-table :data="pagedOrderDetails" v-loading="detailsLoading">
          <el-table-column prop="goods_code" label="物料编码" align="center"></el-table-column>
          <el-table-column prop="goods_name" label="物料名称" align="center"></el-table-column>
          <el-table-column prop="quantity_num" label="采购数量" align="center"></el-table-column>
          <el-table-column prop="unit_price" label="采购单价" align="center"></el-table-column>
          <el-table-column prop="total_price" label="总价" align="center"></el-table-column>
        </el-table>

        <pagination
          v-show="orderDetailsTotal > 0"
          :total="orderDetailsTotal"
          :page.sync="detailsPage.pageNum"
          :limit.sync="detailsPage.pageSize"
          @pagination="handleDetailsPageChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailsVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { listPurchaseOrderDetails,arrivalStorage, selectOrderLine_id, listPurchaseOrders } from "@/views/ck/js/purchase"
export default {
  name: 'ArrivalNotice',
  components: { Pagination },
  data() {
    return {
      loading: false,
      detailList: [],
      total: 0,
      queryParams: {
        po_code: '',
        po_name: '',
        pageNum: 1,
        pageSize: 10
      },
      dialogVisible: false,
      selectedItems: [],
      itemsToStore: {}, // 用于存储所有页面中待入库的商品
      storageDialogPage: {
        pageNum: 1,
        pageSize: 10
      },
      detailsVisible: false,
      currentOrder: null,
      orderDetails: [],
      detailsLoading: false,
      detailsPage: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  computed: {
    canStorage() {
      return Object.keys(this.itemsToStore).length > 0;
    },
    pagedSelectedItems() {
      const start = (this.storageDialogPage.pageNum - 1) * this.storageDialogPage.pageSize;
      const end = start + this.storageDialogPage.pageSize;
      return this.selectedItems.slice(start, end);
    },
    selectedItemsTotal() {
      return this.selectedItems.length;
    },
    pagedOrderDetails() {
      const start = (this.detailsPage.pageNum - 1) * this.detailsPage.pageSize;
      const end = start + this.detailsPage.pageSize;
      return this.orderDetails.slice(start, end);
    },
    orderDetailsTotal() {
      return this.orderDetails.length;
    }
  },
  created() {
    this.getArrivalNoticeList()
  },
  methods: {
    getArrivalNoticeList() {
      console.log("测试获取的到货通知的查询参数：",this.queryParams)
      this.loading = true
      listPurchaseOrderDetails(this.queryParams).then(res => {
        const fetchedRows = res.rows || [];
        fetchedRows.forEach(row => {
          if (this.itemsToStore[row.line_id]) {
            row.delivery_num = this.itemsToStore[row.line_id].delivery_num;
          }
        });
        this.detailList = fetchedRows;
        this.total = res.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getArrivalNoticeList()
    },
    resetQuery() {
      this.queryParams = {
        po_code: '',
        po_name: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getArrivalNoticeList()
    },
    handleDelivery() {
      this.$message.success('配送功能待实现');
    },
    handleDeliveryNumChange(row) {
      if (row.line_id) {
        if (Number(row.delivery_num) > 0) {
          this.$set(this.itemsToStore, row.line_id, row);
        } else {
          this.$delete(this.itemsToStore, row.line_id);
        }
      }
    },
    handleStorage() {
      this.selectedItems = Object.values(this.itemsToStore);
      if (this.selectedItems.length === 0) {
        this.$message.warning("请输入至少一项的本次配送数量");
        return;
      }
      this.storageDialogPage.pageNum = 1;
      this.dialogVisible = true;
    },
    handleStorageConfirm() {
      const loading = this.$loading({
          lock: true,
          text: '正在处理入库操作，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        const update_by = this.$store.getters.name; // 更新人
        // 调用到货入库API
        arrivalStorage(this.selectedItems,update_by).then(response => {
          loading.close();
          if (response.code === 200) {
            this.$message.success('到货入库成功');
            this.getArrivalNoticeList(); // 刷新列表
          } else {
            this.$message.error(response.msg || '到货入库失败');
          }
        }).catch(error => {
          loading.close();
          console.error('到货入库失败:', error);
          this.$message.error('到货入库失败，请稍后重试');
        });
      this.dialogVisible = false;
    },
    handleViewDetails(po_id) {
      this.detailsVisible = true;
      this.detailsLoading = true;
      
      // 获取订单主信息
      listPurchaseOrders({ po_id: po_id, pageNum: 1, pageSize: 1 }).then(response => {
        if (response.rows && response.rows.length > 0) {
          this.currentOrder = response.rows[0];
        }
      }).catch(error => {
        console.error("获取订单主信息失败:", error);
        this.$message.error("获取订单主信息失败");
      });

      // 获取订单行信息
      selectOrderLine_id(po_id).then(response => {
        this.orderDetails = response.rows || [];
        this.detailsLoading = false;
      }).catch(error => {
        console.error("获取订单详情失败:", error);
        this.detailsLoading = false;
        this.$message.error("获取订单详情失败");
      });
    },
    handleDetailsPageChange() {
      // 本地分页，无需操作
    },
    handleStorageDialogPageChange() {
      // 本地分页，无需操作
    },
    handleStorageCancel() {
      this.dialogVisible = false;
      this.$message('已取消入库');
    },
    formatCurrency(num) {
      if (num === null || num === undefined) return '0.00'
      return Number(num).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    formatNumber(num) {
      if (num === null || num === undefined) return '0'
      return Number(num).toLocaleString()
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      let month = '' + (d.getMonth() + 1);
      let day = '' + d.getDate();
      const year = d.getFullYear();
      if (month.length < 2)
        month = '0' + month;
      if (day.length < 2)
        day = '0' + day;
      return [year, month, day].join('-');
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.el-table {
  margin-bottom: 20px;
  width: 100% !important;
}

.el-table th {
  background-color: #f5f7fa;
}

.el-table__body-wrapper {
  width: 100%;
}

.el-table__header-wrapper {
  width: 100%;
}

.el-table .el-table__cell:last-child {
  padding-right: 0 !important;
}

.el-table .el-table__cell:last-child .cell {
  padding-right: 10px !important;
}

.el-table .el-table__cell:last-child .cell {
  text-align: right !important;
}
</style> 